package com.henry.base.concurrency.threadpool;

public class Worker extends Thread{

    private ThreadPool pool;
    private Runnable target;
    private boolean isShutdown=false;
    private boolean isIdle = false;

    public Worker(Runnable target, String name, ThreadPool pool) {
        super(name);
        this.pool = pool;
        this.target = target;
    }

    public Runnable getTarget() {
        return target;
    }
    public boolean isIdle() {
        return isIdle;
    }

    public void run(){
        while (!isShutdown) {
            isIdle = false;
            if (target != null) {
                target.run();//运行任务
            }
            //任务结束
            isIdle=true;
            try {
                //该任务结束后,不关闭线程,而是放入线程池空闲队列
                pool.repool(this);
                synchronized (this) {
                    //线程空闲,等待新的任务到来
                    wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            isIdle=false;
        }
    }

    public synchronized void shutdown() {
        isShutdown=true;
        notifyAll();
    }

    public synchronized void setTarget(Runnable target) {
        this.target=target;
        //设置任务之后,通知run方法,开始执行这个任务
        notifyAll();
    }
}
